<template>
  <div>
    <div class="top-bg" >
      <div class="item">
        <div class="first mr-10">商品名称:</div>
        <el-input placeholder="请输入商品名称" clearable maxlength="50" v-model="params.dishName"></el-input>
      </div>
      <div class="item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetClick">重置</el-button>
<!--        <el-button @click="choseDishExcel">导入商品列表</el-button>-->
      </div>
    </div>
    <div class="bg">
      <el-button type="primary" class="mb-20" @click="addGoodsClick">新增商品</el-button>
      <el-table :data="dataList"  stripe style="width: 100%;" border :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}">
        <el-table-column prop="mainImgs" label="商品主图">
          <template scope="scope">
            <img v-src="scope.row.mainImgs" class="main-img" >
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="categoryName" label="所属分类"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column prop="sort" label="排序">
          <template #default="{row}">
            <el-input v-model="row.sort" @blur="updateSort(row)" oninput="value=value.replace(/[^0-9]/g, '')" placeholder="请输入排序"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="flagSend" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editRow(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     :current-page="params.page" :page-sizes="[10, 20, 30, 50]" :page-size="params.pageSize"
                     :layout="params.total<10?'->,total':'->,total, sizes, prev, pager, next, jumper'" :total="params.total">
      </el-pagination>
    </div>
    <order-post :edit-row="currentDish" :title="isEdit?'编辑':'新增'" v-if="orderPostFlag" :show-flag.sync="orderPostFlag" @closeDialog="closeDialog"></order-post>
    <input type="file" ref="fileExcel" :multiple="false"  style="display: none" accept=".xls,.xlsx" @change="handleChange"></input>
  </div>
</template>

<script>
import {
  KAFEE_GET_GOODS_LIST, KAFEE_POST_DELETE_DISH, KAFEE_POST_EDIT_DISH,
  ORDERING_CHANGE_SCORE_BY_ORDER_DISH,
  ORDERING_GET_GEARS_LIST,
  ORDERING_ORDERING_LIST_GET, ORDERING_ORDERING_POST,
  ORDERING_POST_ORDERING_DELETE, ORDERING_POST_ORDERING_ORDER, ORDERING_POST_USER_ORDER_DELETE
} from "@/assets/const/api";
import {getStore} from "js-utils";
import * as XLSX from '@/config/xlsx.mini'
import {readFile, excelSerialToDateString, getUserInfo} from "@/config/tools";
import {Validate} from "js-utils/validate";
import OrderPost from "@/views/ordering/orderPost.vue";
export default {
    name: '',
    mixins: [],
    components: {OrderPost},
    props: {},
    data () {
        return {
          dataList:[],
          fileObj:null,
          orderPostFlag:false,
          submitData:{
            dishId:'',
            dishName:'',
            timeRange:0,
            flagSend:0,
            targetDate:'',
            orderCount:1,
            pickUpCount:0,
            remark:'',
            isPackage:0,
          },
          currentDish:{},
          params:{
            current:1,
            size:10,
            total:0,
            dishName:'',
          },
        }
    },
    computed: {
      isEdit(){
        if (Validate.isEmpty(this.currentDish)){
          return false
        }
        return true;
      },
      userInfo(){
        return this.$store.state.userInfo||{};
      }
    },
    watch: {},
    created() {
      this.resetData();
      this.getData()
    },
    mounted () {},
    methods: {
      getData(){
        this.$http.get(KAFEE_GET_GOODS_LIST,this.params).then(res => {
          this.dataList = res.data?.records||[];
          this.params.total = res.data.total||0;
        });
      },
      handleCurrentChange(val){
        this.params.current = val
        this.getData()
      },
      handleSizeChange(val){
        this.params.pageSize = val
        this.getData()
      },
      editRow(row){
        this.currentDish = row;
        this.orderPostFlag = true;
      },
      deleteClick(row){
        this.$confirm('确认删除该条商品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post(KAFEE_POST_DELETE_DISH,{id:row.id}).then(res=>{
            if(res.code === 200){
              this.$message.success('操作成功');
              this.getData();
            }
          })
        }).catch(()=>{})
      },
      updateSort(row){
        this.$http.post(KAFEE_POST_EDIT_DISH,row).then(res => {
            this.$message.success('更新成功');
            this.getData();
        });
      },
      handleSearch(){
        this.params.current = 1;
        this.getData()
      },
      resetData(){
        this.params = {current: 1,size:10,total:0}
      },
      resetClick(){
        this.resetData()
        this.getData()
      },
      submitBatch(list){
        let dic = {dishList:list}
        this.$http.post(ORDERING_ORDERING_POST,dic).then(res=>{
          if(res.code === 200){
            this.$message.success('提交成功')
            this.resetClick()
          }
        })
      },
      async handleChange(e) {
        if (e.target.files.length === 0) {
          this.$message.error('选择文件不能为空')
          return
        }
        this.fileObj = e
        let fileName = e.target.value.split('\\').pop().replace(/\..+$/, "");
        if (!fileName || fileName.length === 0) {
          fileName = 'thirdCustomer'
        }
        let file = e.target.files[0]
        this.fileObj = file
        let data = await readFile(file)
        let workbook = XLSX.read(data, { type: "binary" });

        //拿到第一个sheet表的数据，把第一个表格的数据转换成JSON数据
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        let dataJsons = XLSX.utils.sheet_to_json(worksheet);
        console.log(dataJsons)
        if (!Validate.isEmpty(dataJsons)){
          dataJsons.forEach(e=>{
            e['生效日期'] = excelSerialToDateString(e['生效日期'])
          })
          let finalList = []
          dataJsons.forEach(e=>{
            let dic = {dishName:e['商品名称'],  timeRange:e['档位名称']==='早餐'?5:e['档位名称']==='午餐'?6:e['档位名称']==='晚餐'?7:8,
              createPerson:this.userInfo.id, remark:'',
              flagSend:false,targetDate:e['生效日期'], dishLimit:1}
            finalList.push(dic)
          })
          this.submitBatch(finalList)
        }
      },
      addGoodsClick(){
        this.currentDish = {};
        this.orderPostFlag = true;
      },
      closeDialog(){
        this.orderPostFlag = false;
        this.getData();
      }
    }
}
</script>

<style scoped lang="scss">
.bg{
  background-color: white;
  padding: 20px;
}
.main-img{
  width: 40px;
  height: 40px;
  border-radius: 4px;
}
.top-bg{
  background-color: #f9f9f9;
  border: 1px solid #ebeef5;
  min-height: 60px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  padding: 18px 0 0;
  display: flex;
  align-items: center;
  .item{
    display: flex;
    align-items: center;
    margin-right: 10px;
    margin-bottom: 18px;
    flex-shrink: 0;

  }
  .first{
    min-width: 100px;
    text-align: right;
  }
}
</style>